interface SearchServiceResData<T> {
  code: number
  data: T[]
  msg: string
  time: string
}

type SearchService<T> = () => Promise<SearchServiceResData<T>>

export function useSearch<T extends Record<string, any>>(service: SearchService<T>) {
  // 搜索框内容
  const searchText = ref('')
  // 是否处于搜索状态
  const isOpenSearch = ref(false)
  // 搜索中
  const searching = ref(false)
  // 搜索结果
  const searchResult = ref<T[]>([]) as Ref<T[]>

  // 搜索请求
  const fetchSearchResult = useThrottleFn(async () => {
    searching.value = true
    try {
      const res = await service()
      if (res.code === 1) {
        searchResult.value = res.data
        searching.value = false
      }
      else {
        uni.showToast({ title: res.msg, icon: 'none' })
        searching.value = false
      }
    }
    catch (error: any) {
      uni.showToast({ title: `搜索失败，${error.message}`, icon: 'none' })
      searching.value = false
    }
  }, 1000)

  return { searchText, isOpenSearch, searching, searchResult, fetchSearchResult }
}
